<script setup>
import { ref, onMounted } from 'vue'
import api from '../api/products_api.js'
import categoriesApi from '../api/categories_api.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// ---------------------- 表格数据 ----------------------
const tableData = ref([])
const total = ref(0)

// ---------------------- 分页 ----------------------
const searchObj = ref({
  current: 1,
  limit: 10,
  productName: '' // 支持模糊查询
})

// ---------------------- 新增/编辑对象 ----------------------
const newProduct = ref({
  productName: '',
  category: null,
  sellerId: '',
  sellerName: '',
  productPrice: null,
  description: ''
})

const editProduct = ref({})

// ---------------------- 弹窗 ----------------------
const addWinVisible = ref(false)
const editWinVisible = ref(false)

// ---------------------- 分类下拉 ----------------------
const categoryOptions = ref([])

// ---------------------- 加载商品 ----------------------
const loadProducts = async () => {
  try {
    const res = await api.page(searchObj.value)
    tableData.value = res.data || []
    total.value = res.count || 0
  } catch (error) {
    console.error(error)
    tableData.value = []
    total.value = 0
  }
}

// ---------------------- 加载分类 ----------------------
const loadCategories = async () => {
  try {
    const res = await categoriesApi.all()
    if (!Array.isArray(res)) {
      categoryOptions.value = []
      return
    }
    // 根据 categories 的实际数据结构调整映射
    categoryOptions.value = res.map(item => ({
      label: item.categoryName,
      value: item.categoryName
    }))
  } catch (error) {
    console.error(error)
    categoryOptions.value = []
  }
}

// ---------------------- 页面加载 ----------------------
onMounted(async () => {
  await loadProducts()
  await loadCategories()
})

// ---------------------- 查询 ----------------------
const handleSearch = () => {
  searchObj.value.current = 1
  loadProducts()
}

// ---------------------- 分页 ----------------------
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  loadProducts()
}
const handleCurrentChange = (val) => {
  searchObj.value.current = val
  loadProducts()
}

// ---------------------- 新增 ----------------------
const showAddDialog = () => {
  newProduct.value = { productName: '', category: null, sellerId: '', sellerName: '', productPrice: null, photo: ''  }
  addWinVisible.value = true
}
const addCancel = () => {
  newProduct.value = {}
  addWinVisible.value = false
}
const addCommit = async () => {
  if (!newProduct.value.productName || !newProduct.value.category || !newProduct.value.sellerId || !newProduct.value.sellerName || newProduct.value.productPrice == null) {
    ElMessage.warning('请填写完整信息')
    return
  }
  try {
    await api.add({ ...newProduct.value })
    ElMessage.success('新增成功')
    await loadProducts()
    addWinVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('新增失败')
  }
}

// ---------------------- 编辑 ----------------------
const handleEdit = (index, row) => {
  editProduct.value = { ...row }
  editWinVisible.value = true
}
const editCancel = () => {
  editProduct.value = {}
  editWinVisible.value = false
}
const editCommit = async () => {
  if (!editProduct.value.productName || !editProduct.value.category || !editProduct.value.sellerId || !editProduct.value.sellerName || editProduct.value.productPrice == null) {
    ElMessage.warning('请填写完整信息')
    return
  }
  try {
    await api.edit({ ...editProduct.value })
    ElMessage.success('修改成功')
    await loadProducts()
    editWinVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('修改失败')
  }
}

// ---------------------- 删除 ----------------------
const handleDelete = (index, row) => {
  ElMessageBox.confirm('确认删除该商品吗?', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await api.del(row.productId)
    searchObj.value.current = 1
    await loadProducts()
    ElMessage.success('删除成功')
  }).catch(() => {})
}
//定义增加图片后的方法（编辑时的照片处理）
const handleUploadSuccess = (response, file) => {
  editProduct.value.photo = response.data
  console.log('图片上传成功:', response.data)
}

// 新增商品上传成功(新增)
const handleAddUploadSuccess = (response, file) => {
  newProduct.value.photo = response.data;
  console.log('新增商品图片上传成功:', response.data);
}


</script>

<template>
  <div style="padding: 20px;">
    <h2>商品列表</h2>

    <!-- 查询 -->
    <el-form :inline="true" :model="searchObj" style="margin-bottom: 10px;">
      <el-form-item label="商品id">
        <el-input v-model="searchObj.productId" placeholder="请输入商品id" clearable />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="searchObj.productName" placeholder="请输入商品名称" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="primary" @click="showAddDialog">新增商品</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="productId" label="商品ID" width="80" />
      <el-table-column prop="productName" label="商品名称" width="150" />
      <el-table-column prop="category" label="商品分类" width="100" />
      <el-table-column prop="sellerId" label="卖家ID" width="100" />
      <el-table-column prop="sellerName" label="卖家用户名" width="120" />
      <el-table-column prop="productPrice" label="价格" width="100" />
      <el-table-column prop="productTime" label="发布时间" width="180" />
      <!-- 新增商品描述列 -->
      <el-table-column prop="description" label="商品描述" width="200" />
      <el-table-column prop="photo" label="商品实物图片" width="120">
        <template #default="scope">
          <img :src="scope.row.photo || 'src/assets/shop.png'" style="width: 100px; height: 100px;"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :total="total"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 新增弹窗 -->
    <el-dialog v-model="addWinVisible" title="新增商品" width="500">
      <el-form :model="newProduct" label-width="100px">
        <el-form-item label="商品名称"><el-input v-model="newProduct.productName" /></el-form-item>
        <el-form-item label="分类"><el-select v-model="newProduct.category" placeholder="请选择分类"><el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
        <el-form-item label="卖家ID"><el-input v-model="newProduct.sellerId" /></el-form-item>
        <el-form-item label="卖家用户名"><el-input v-model="newProduct.sellerName" /></el-form-item>
        <el-form-item label="价格"><el-input v-model="newProduct.productPrice" type="number" /></el-form-item>
        <!-- 新增商品描述字段 -->
        <el-form-item label="商品描述">
          <el-input
              v-model="newProduct.description"
              type="textarea"
              placeholder="请输入商品描述"
              :rows="3" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleAddUploadSuccess"
          >
            <img v-if="newProduct.photo" :src="newProduct.photo" style="width: 100px; height: 100px"/>
            <img v-else src="@/assets/shop.png" style="width:100px" />
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">提交</el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editWinVisible" title="编辑商品" width="500">
      <el-form :model="editProduct" label-width="100px">
        <el-form-item label="商品名称"><el-input v-model="editProduct.productName" /></el-form-item>
        <el-form-item label="分类"><el-select v-model="editProduct.category" placeholder="请选择分类"><el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
        <el-form-item label="卖家ID"><el-input v-model="editProduct.sellerId" /></el-form-item>
        <el-form-item label="卖家用户名"><el-input v-model="editProduct.sellerName" /></el-form-item>
<!--        <el-form-item label="价格"><el-input v-model="editProduct.productPrice" type="number" /></el-form-item>-->
        <!-- 新增商品描述字段 -->
        <el-form-item label="商品描述">
          <el-input
              v-model="editProduct.description"
              type="textarea"
              :rows="3" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="/api/upload/file"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
          >
            <img v-if="editProduct.photo" :src="editProduct.photo" style="width: 100px; height: 100px"/>
            <img v-else src="@/assets/shop.png" style="width:100px" />
          </el-upload>


        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">提交</el-button>
      </template>
    </el-dialog>

  </div>
</template>
<style scoped>
h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>